'use strict'

let playerSessionMgr = require('../core/playerSessionMgr')
let WebSocket = require('ws')
let nodeServerConfig = require('../../config/serverConfig').nodeServerConfig
let routes = require('./route')
let util = require('util')

class GateHandle {
  constructor() {
    this.gateClient = null
    this.callbacks = {}
    this.reqId = 1
  }

  createClient() {
    let self = this
    let gateClient = new WebSocket(`ws://${nodeServerConfig.ip}:${nodeServerConfig.port}`)
    this.gateClient = gateClient
    gateClient.on('open', function open() {
      console.log('连接网关服务器成功')
      self.callRemoteFunc('bindNodeName', {
        nodeName: 'node1'
      })

      self.callRemoteFunc('getRequestRoute', {
        routeName: routes.routemap,
        nodeName: 'node1'
      })
    })

    gateClient.on('message', function message(data, flags) {
      try {
        data = JSON.parse(data)
        if (!util.isObject(data.msg)) {
          data.msg = {}
        }
      } catch (e) {
        return
      }
      Log(data)
      let pId = data.pId

      let method
      if (pId) {
        let player = playerSessionMgr.getPlayer(pId)
        if (!player) {
          return
        }
        method = routes.getLogin(data.route)
        if (method) {
          Log('接受有效消息')
          method(player, data.msg, function(result) {
            if (typeof result === 'number') {
              result = {
                error: result
              }
            }
            self.sendMsg(result, data.reqId)
          })
        }
      } else {
        method = routes.getNotLogin(data.route)
        if (method) {
          Log('接受有效消息')
          method(data.msg, function(result) {
            if (typeof result === 'number') {
              result = {
                error: result
              }
            }
            self.sendMsg(result, data.reqId)
          })
        }
      }
    })

    gateClient.on('close', function close() {
      //保存所有用户后清空 session
      console.log('网关服务器断开连接')
      self.gateClient = {}
      self.gateClient.send = function(){}
    })
  }

  sendMsg(msg, reqId) {
    var sendData = {}
    if (reqId) {
      sendData['reqId'] = reqId
    }
    sendData['msg'] = msg
    sendData = JSON.stringify(sendData)
    this.gateClient.send(sendData)
  }

  //调用根节点的远程方法
  callRemoteFunc(route, msg) {
    var sendData = {
      msg: msg,
      route: route
    }
    sendData = JSON.stringify(sendData)
    this.gateClient.send(sendData)
  }
}

let gateHandle = new GateHandle()
gateHandle.createClient()
module.exports = gateHandle
